﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GBMS.APP;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using System.Configuration;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using KPIS.GERP.GBMS.MODEL;
using System.Collections;
using System.Threading;
using System.Security;

namespace KPIS.GERP.GBMS.APP_UI
{
    public partial class BGM_Project_Report : System.Web.UI.Page
    {
        private ManageProject projectBLL = new ManageProject();
        private IProject pjBLL = new Project_BLL();
        private ProjectPass projectPass = new ProjectPass();
        private ProjectControl_BLL ctrl = new ProjectControl_BLL();
        private ProjectOperation projectOperation = new ProjectOperation();
        private D_BGM_ProjectOperationReport operRepBLL = new D_BGM_ProjectOperationReport();
        private ComboBLL combo = new ComboBLL();
        private Common.Main main = new Common.Main();

        protected void Page_Load(object sender, System.EventArgs e)
        {
            hdHeaderID.Value = Request.QueryString["id"].ToString();

            if (!IsPostBack)
            {
                LoadData();
                LoadDDLBgmScopeSeq();
                LoadDDLPrjTypeSeq();

                foreach (RepeaterItem item in repeaterJobSitePass.Items)
                {
                    ImageButton btn = (ImageButton)item.FindControl("cmdDelete");

                    if (btn != null)
                    {
                        btn.Visible = false;
                    }
                }

                btnJobSitePass.Visible = false;
            }
        }

        private void LoadData()
        {
            DataTable dt = pjBLL.GetDataProjectBySequence(hdHeaderID.Value);
            Session["ProjectID"] = hdHeaderID.Value;

            if(dt.Rows.Count > 0)
            {
                lbBgmYear.Text = main.WebString(dt.Rows[0]["bgm_year"].ToString());
                lbBgmProjCode.Text = main.WebString(dt.Rows[0]["bgm_prj_code"].ToString());
                litTitle.Text = main.WebString(dt.Rows[0]["bgm_prj_name"].ToString());
                hdnProjectName.Value = main.WebString(dt.Rows[0]["bgm_prj_name"].ToString());
                lbOutPut.Text = dt.Rows[0]["output_name"].ToString();
                lbAct.Text = dt.Rows[0]["act_name"].ToString();
                lbSubAct.Text = main.WebString(dt.Rows[0]["bgm_strat_list_name"].ToString());
                lbJobSite.Text = main.WebString(dt.Rows[0]["job_site_name"].ToString());
                lbJobSiteMain.Text = main.WebString(dt.Rows[0]["job_site_name_main"].ToString());
                lbBgmReqScopeSeq.Text = main.WebString(dt.Rows[0]["bgm_prj_scope"].ToString());
                lbBgmReqScopeName.Text = main.WebString(dt.Rows[0]["bgm_scope_name"].ToString());
                lbPrjTypeName.Text = main.WebString(dt.Rows[0]["prj_type_name"].ToString());
                lbStartDate.Text = Convert.ToDateTime(dt.Rows[0]["date_start"]).ToShortDateString();
                lbEndDate.Text = Convert.ToDateTime(dt.Rows[0]["date_end"]).ToShortDateString();
                lbGFMISCode.Text = main.WebString(dt.Rows[0]["gfmis_code"].ToString());
                lblStatus.Text = main.WebString(dt.Rows[0]["record_status"].ToString());
                lblStatusName.Text = main.WebString(dt.Rows[0]["record_status_name"].ToString());
                string strWorkingJobsiteSeq = new SsMng().GetUss(SsMng.SsUserType.WorkingJobSiteSeq).ToString();

                bool bOwn = strWorkingJobsiteSeq == dt.Rows[0]["job_site_seq"].ToString() || strWorkingJobsiteSeq == dt.Rows[0]["job_site_seq_main"].ToString();
                cmdEdit.Enabled = bOwn;
                //btnChangeExp.Enabled = bOwn;
                //btnReturnBudget.Enabled = bOwn;

                string strBgmReqObject = main.WebString(dt.Rows[0]["bgm_prj_object"].ToString());
                string strBgmReqPlan = main.WebString(dt.Rows[0]["bgm_prj_plan"].ToString());
                string strBgmReqReason = main.WebString(dt.Rows[0]["bgm_prj_reason"].ToString());
                string strBgmReqRemark = main.WebString(dt.Rows[0]["bgm_prj_remark"].ToString());
                string strBgmReqTarget = main.WebString(dt.Rows[0]["bgm_prj_target"].ToString());

                lbBgmReqObjectFull.Text = strBgmReqObject;
                lbBgmReqPlanFull.Text = strBgmReqPlan;
                lbBgmReqReasonFull.Text = strBgmReqReason;
                lbBgmReqRemarkFull.Text = strBgmReqRemark;
                lbBgmReqTargetFull.Text = strBgmReqTarget;

                if (strBgmReqObject.Length > 70)
                {
                    strBgmReqObject = strBgmReqObject.Substring(0, 70) + "...";
                    lbBgmReqObject.Text = strBgmReqObject;
                    cmdSeeMore2.Visible = true;
                }

                if (strBgmReqPlan.Length > 70)
                {
                    strBgmReqPlan = strBgmReqPlan.Substring(0, 70) + "...";
                    lbBgmReqPlan.Text = strBgmReqPlan;
                    cmdSeeMore4.Visible = true;
                }

                if (strBgmReqReason.Length > 70)
                {
                    strBgmReqReason = strBgmReqReason.Substring(0, 70) + "...";
                    lbBgmReqReason.Text = strBgmReqReason;
                    cmdSeeMore1.Visible = true;
                }

                if (strBgmReqRemark.Length > 70)
                {
                    strBgmReqRemark = strBgmReqRemark.Substring(0, 70) + "...";
                    lbBgmReqRemark.Text = strBgmReqRemark;
                    cmdSeeMore5.Visible = true;
                }

                if (strBgmReqTarget.Length > 70)
                {
                    strBgmReqTarget = strBgmReqTarget.Substring(0, 70) + "...";
                    lbBgmReqTarget.Text = strBgmReqTarget;
                    cmdSeeMore3.Visible = true;
                }
            }

            repeaterJobSitePass.DataSource = projectPass.GetData(hdHeaderID.Value);
            repeaterJobSitePass.DataBind();

            //tvlExpense.DataSource = projectBLL.GetReportTreeList(hdHeaderID.Value);
            //tvlExpense.DataBind();

            //tvlOperation.DataSource = projectBLL.GetReport(hdHeaderID.Value);
            //tvlOperation.DataBind();
            gridReport5.DataSource = projectBLL.GetTransferReport(hdHeaderID.Value);
            gridReport5.DataBind();
        }

        protected void LoadDDLBgmScopeSeq()
        {
            ddlBgmScopeSeq.DataSource = combo.ListScope();
            ddlBgmScopeSeq.DataBind();
        }

        protected void LoadDDLPrjTypeSeq()
        {
            ddlPrjTypeSeq.DataSource = combo.ListProjectType();
            ddlPrjTypeSeq.DataBind();
        }

        protected void SetSumExpense(DataTable dtb)
        {
            double dblSumExpense = 0;

            foreach (DataRow dtr in dtb.Rows)
            {
                string strGroup = dtr["child_value"].ToString().Split('-')[1];

                if (strGroup == "SOURCE")
                {
                    dblSumExpense += Convert.ToDouble(dtr["cal_amount"]);
                }
            }

            lblSumExpense.Text = dblSumExpense.ToString("#,##0.00");
        }

        protected void gridTotalReport_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_source_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridReport1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridReport2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridReport3_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridReport4_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridReport5_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_exp_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            string strArg = e.Argument;

            if (strArg == "JobSitePass")
            {
                repeaterJobSitePass.DataSource = projectPass.GetData(hdHeaderID.Value);
                repeaterJobSitePass.DataBind();
            }
            else
            {
                //LoadDataGrid();
            }
        }

        protected void btnCloseProject_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnChangeExp_Click(object sender, EventArgs e)
        {

        }

        protected void btnChangePlan_Click(object sender, EventArgs e)
        {

        }

        protected void btnReturnBudget_Click(object sender, EventArgs e)
        {

        }

        protected void lbReport2_Click(object sender, EventArgs e)
        {

        }
        protected void lbReport3_Click(object sender, EventArgs e)
        {

        }
        protected void lbReport4_Click(object sender, EventArgs e)
        {

        }

        public void OpenPopup(Page p, string strPath, string strPopupName, string[] value)
        {
            string strScript = "openProjectOperationReport('')";

            ScriptManager.RegisterClientScriptBlock(p, p.GetType(), "onclick"
                , strScript, true);
        }

        protected void gridReport1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        protected void cmdSeeMore1_Click(object sender, EventArgs e)
        {
            lbBgmReqReason.Visible = false;
            lbBgmReqReasonFull.Visible = true;
            cmdSeeMore1.Visible = false;
        }

        protected void cmdSeeMore2_Click(object sender, EventArgs e)
        {
            lbBgmReqObject.Visible = false;
            lbBgmReqObjectFull.Visible = true;
            cmdSeeMore2.Visible = false;
        }

        protected void cmdSeeMore3_Click(object sender, EventArgs e)
        {
            lbBgmReqTarget.Visible = false;
            lbBgmReqTargetFull.Visible = true;
            cmdSeeMore3.Visible = false;
        }

        protected void cmdSeeMore4_Click(object sender, EventArgs e)
        {
            lbBgmReqPlan.Visible = false;
            lbBgmReqPlanFull.Visible = true;
            cmdSeeMore4.Visible = false;
        }

        protected void cmdSeeMore5_Click(object sender, EventArgs e)
        {
            lbBgmReqRemark.Visible = false;
            lbBgmReqRemarkFull.Visible = true;
            cmdSeeMore5.Visible = false;
        }

        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            txtBgmProjCode.Text = lbBgmProjCode.Text;
            txtProjectName.Text = litTitle.Text;
            txtGFMISCode.Text = lbGFMISCode.Text;
            dpStartDate.SetValue(lbStartDate.Text);
            dpEndDate.SetValue(lbEndDate.Text);
            ddlBgmScopeSeq.SelectedValue = lbBgmReqScopeSeq.Text;
            ddlPrjTypeSeq.SelectedValue = lbPrjTypeSeq.Text;
            txtBgmReqReason.Text = main.LabelToTextbox(lbBgmReqReasonFull.Text);
            txtBgmReqObject.Text = main.LabelToTextbox(lbBgmReqObjectFull.Text);
            txtBgmReqTarget.Text = main.LabelToTextbox(lbBgmReqTargetFull.Text);
            txtBgmReqPlan.Text = main.LabelToTextbox(lbBgmReqPlanFull.Text);
            txtBgmReqRemark.Text = main.LabelToTextbox(lbBgmReqRemarkFull.Text);

            SetEditMode(true);
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string strProjectName = txtProjectName.Text;
            Nullable<DateTime> dStartDate = dpStartDate.GetDateValue();
            Nullable<DateTime> dEndDate = dpEndDate.GetDateValue();
            string strBgmScopeSeq = ddlBgmScopeSeq.SelectedValue;
            string strPrjTypeSeq = ddlPrjTypeSeq.SelectedValue;
            string strBgmReqReason = txtBgmReqReason.Text;
            string strBgmReqObject = txtBgmReqObject.Text;
            string strBgmReqTarget = txtBgmReqTarget.Text;
            string strBgmReqPlan = txtBgmReqPlan.Text;
            string strBgmReqRemark = txtBgmReqRemark.Text;

            if (dStartDate == null)
            {
                main.MessageAlert(Page, "");
                return;
            }
            else if (dEndDate == null)
            {
                main.MessageAlert(Page, "");
                return;
            }
            else if (strBgmScopeSeq.Length == 0)
            {
                main.MessageAlert(Page, "");
                return;
            }
            else if (strPrjTypeSeq.Length == 0)
            {
                main.MessageAlert(Page, "");
                return;
            }

            projectBLL.UpdateProject(hdHeaderID.Value, txtBgmProjCode.Text, strProjectName
                , null, null, strBgmScopeSeq, strBgmReqReason, strBgmReqObject, strBgmReqTarget
                , strBgmReqPlan, strBgmReqRemark, strPrjTypeSeq, dStartDate.Value, dEndDate.Value
                , txtGFMISCode.Text, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));

            LoadData();
            SetEditMode(false);
        }

        protected void SetEditMode(bool bEdit)
        {
            cmdEdit.Visible = !bEdit;
            cmdSave.Visible = bEdit;
            cmdEndProject.Visible = !bEdit && lblStatus.Text != "D";
            
            lbBgmProjCode.Visible = !bEdit;
            lbGFMISCode.Visible = !bEdit;
            lbStartDate.Visible = !bEdit;
            lbEndDate.Visible = !bEdit;
            lbBgmReqScopeName.Visible = !bEdit;

            lbBgmReqReason.Visible = !bEdit;
            lbBgmReqReasonFull.Visible = !bEdit;
            cmdSeeMore1.Visible = !bEdit;

            lbBgmReqObject.Visible = !bEdit;
            lbBgmReqObjectFull.Visible = !bEdit;
            cmdSeeMore2.Visible = !bEdit;

            lbBgmReqTarget.Visible = !bEdit;
            lbBgmReqTargetFull.Visible = !bEdit;
            cmdSeeMore3.Visible = !bEdit;

            lbBgmReqPlan.Visible = !bEdit;
            lbBgmReqPlanFull.Visible = !bEdit;
            cmdSeeMore4.Visible = !bEdit;

            lbBgmReqRemark.Visible = !bEdit;
            lbBgmReqRemarkFull.Visible = !bEdit;
            cmdSeeMore5.Visible = !bEdit;

            txtBgmProjCode.Visible = bEdit;
            txtGFMISCode.Visible = bEdit;
            panelProjectName.Visible = bEdit;
            dpStartDate.Visible = bEdit;
            dpEndDate.Visible = bEdit;
            ddlBgmScopeSeq.Visible = bEdit;
            ddlPrjTypeSeq.Visible = bEdit;
            txtBgmReqReason.Visible = bEdit;
            txtBgmReqObject.Visible = bEdit;
            txtBgmReqTarget.Visible = bEdit;
            txtBgmReqPlan.Visible = bEdit;
            txtBgmReqRemark.Visible = bEdit;

            foreach (RepeaterItem item in repeaterJobSitePass.Items)
            {
                ImageButton btn = (ImageButton)item.FindControl("cmdDelete");

                if (btn != null)
                {
                    btn.Visible = bEdit;
                }
            }

            btnJobSitePass.Visible = bEdit;
        }

        protected void repeaterJobSitePass_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string strProjectSeq = hdHeaderID.Value;
                Label lblBgmProjPassSeq = (Label)e.Item.FindControl("lblBgmProjPassSeq");
                projectPass.Delete(lblBgmProjPassSeq.Text, new SsMng().EmpSeq);

                repeaterJobSitePass.DataSource = projectPass.GetData(strProjectSeq);
                repeaterJobSitePass.DataBind();
            }
        }

        protected void tvlExpense_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            DataTable dtb = projectBLL.GetReportTreeList(hdHeaderID.Value);
            tvlExpense.DataSource = dtb;

            SetSumExpense(dtb);
        }

        protected void cmdEndProject_Click(object sender, EventArgs e)
        {
            string strBgmProjSeq = hdHeaderID.Value;
            string strEmpSeq = new SsMng().EmpSeq;

            if (projectOperation.CountProjectOperation(strBgmProjSeq) > 0)
            {
                main.MessageAlert(Page, "กรุณาปิดอนุมัติโครงการให้หมดก่อนที่จะปิดโครงการ!!");
                return;
            }

            try
            {
                DataTable dtb = projectBLL.GetProjectExpenseWithRemainAmount(hdHeaderID.Value, null, null);

                foreach (DataRow dtr in dtb.Rows)
                {
                    Nullable<double> dAmount = main.ConvertNullDouble(dtr["total_amount"]);

                    if (dAmount != null && dAmount > 0)
                    {
                        string strBgmProjCtrlSeq = "";
                        string strBgmProjExpSeq = main.WebString(dtr["bgm_proj_exp_seq"].ToString());
                        string strBgmSourceSeq = main.WebString(dtr["bgm_source_seq"].ToString());
                        string strBgmStratListSeq = main.WebString(dtr["bgm_strat_list_seq"].ToString());
                        string strJobSiteSeq = main.WebString(dtr["job_site_seq"].ToString());
                        string strBgmExpGrpSeq = main.WebString(dtr["bgm_exp_grp_seq"].ToString());
                        string strAmount = main.WebString(dtr["cal_amount"].ToString());

                        DataTable dtbProjectCtrl = ctrl.FindProjectCtrl(lbBgmYear.Text, strBgmStratListSeq, strBgmSourceSeq
                            , strJobSiteSeq, strBgmExpGrpSeq);

                        if (dtbProjectCtrl.Rows.Count > 0)
                        {
                            strBgmProjCtrlSeq = dtbProjectCtrl.Rows[0]["bgm_proj_ctrl_seq"].ToString();
                        }
                        else
                        {
                            strBgmProjCtrlSeq = ctrl.Insert_BgmProjectControl(lbBgmYear.Text, strBgmSourceSeq
                                , strBgmStratListSeq, strJobSiteSeq, strBgmExpGrpSeq, strEmpSeq);
                        }

                        ctrl.Insert_BgmProjectControlExpense(strBgmProjCtrlSeq, "1", strBgmProjExpSeq, strAmount, strEmpSeq);
                        pjBLL.UpdateTotalAmountProjectExpense(strBgmProjExpSeq, "ปิดโครงการ", strAmount, "-" + strAmount
                            , "2", strEmpSeq);

                    }
                }

                pjBLL.DeleteProject(strBgmProjSeq, strEmpSeq);
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "onclick"
                    , "closeRadWindow", true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void tvlOperation_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            tvlOperation.DataSource = projectBLL.GetProjectOperationReport(hdHeaderID.Value);
        }

        protected void tvlOperation_ItemDataBound(object sender, TreeListItemDataBoundEventArgs e)
        {
            if (e.Item.ItemType == TreeListItemType.Item || e.Item.ItemType == TreeListItemType.AlternatingItem)
            {
                TreeListDataItem item = (TreeListDataItem)e.Item;
                bool bRoot = item["child_seq"].Text.Split('/').Length == 2;

                ((Label)item["name"].FindControl("lblName")).Visible = !bRoot;
                ((LinkButton)item["name"].FindControl("cmdViewOperation")).Visible = bRoot;

                if (bRoot)
                {
                    item.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    item.ForeColor = System.Drawing.Color.Black;
                }
            }
        }
    }
}